package lab.anoper.juc;

import java.util.concurrent.CountDownLatch;

/**
 * @author 闫家洪（yanjiahong@vcredit.com）
 * @since 2024/12/11
 */
public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个 CountDownLatch，初始计数器值为 3
        CountDownLatch latch = new CountDownLatch(3);

        // 创建并启动 3 个线程
        Thread thread1 = new Thread(new Worker(latch), "Thread-1");
        Thread thread2 = new Thread(new Worker(latch), "Thread-2");
        Thread thread3 = new Thread(new Worker(latch), "Thread-3");

        thread1.start();
        thread2.start();
        thread3.start();

        // 主线程等待，直到计数器为 0
        latch.await();
        System.out.println("All threads have finished their work. Main thread resumes.");
    }

    static class Worker implements Runnable {
        private final CountDownLatch latch;

        public Worker(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                // 模拟线程执行任务
                System.out.println(Thread.currentThread().getName() + " is working...");
                Thread.sleep(1000); // 模拟工作时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                // 完成工作后调用 countDown()
                System.out.println(Thread.currentThread().getName() + " has finished.");
                latch.countDown();
            }
        }
    }

}

